﻿using DDBS_Server.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;

namespace DDBS_Server.APIControllers
{
    public class SamplesController : ApiController
    {
        public string Get()
        {
            return "SamplesAPIController";
        }

        [Route("api/samples/putindexes")]
        [HttpGet]
        public string[] PutIndexes()
        {
            RavenDB DB = new RavenDB();
            return DB.PutIndexes();
        }

        [Route("api/samples/shardlist")]
        [HttpGet]
        public string ShardList()
        {
            RavenDB DB = new RavenDB();
            string shardlist = String.Join(";", DB.GetShardNames());
            return shardlist;
        }
        
        [Route("api/samples/getall")]
        [HttpGet]
        public List<Sample> GetAll()
        {
            RavenDB DB = new RavenDB();
            return DB.GetAllSamples();
        }


        // GET: api/Samples/{int}
        // Store generated sample - for testing only.
        public string Get(int id)
        {
            Random rand = new Random();
            Sample s1 = new Sample();
            s1.Name = "Sample "+id.ToString();
            s1.Shard = "JG1";
            s1.Peaks = new List<Peak>() { new Peak(id, rand.Next(1, 200)), new Peak(id + 0.2, rand.Next(1, 200)), new Peak(id + 0.3, rand.Next(1, 200)), new Peak(id - 0.05, rand.Next(1, 200)), new Peak(id - 0.38, rand.Next(1, 200)), new Peak(id - 0.4, rand.Next(1, 200)), new Peak(id - 0.52, rand.Next(1, 200)), new Peak(id - 0.8, rand.Next(1, 200)), new Peak(id - 0.83, rand.Next(1, 200)), new Peak(id - 0.87, rand.Next(1, 200)) };

            RavenDB DB = new RavenDB();
            return DB.StoreSample(s1);
        }

        [Route("api/samples/getsamplesbtp")]
        [HttpPost]
        public List<Sample> GetSamples([FromBody] SamplesRequest request)
        {
            RavenDB DB = new RavenDB();
            return DB.GetSamplesByTopPeaks(request.simSample, request.tolerance, request.ratioTolerance);
        }

        [Route("api/samples/storeRandSamples")]
        [HttpPost]
        public string storeRandSamples([FromBody] List<Sample> samples)
        {
            RavenDB DB = new RavenDB();
            foreach (Sample s in samples) DB.StoreSample(s);
            return "stored";
        }

        [Route("api/samples/storeSamples")]
        [HttpPost]
        public async Task<HttpResponseMessage> StoreSamples()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                //Store file to RavenDB FileSystem
                foreach (MultipartFileData file in provider.FileData)
                {
                    RavenDB DB = new RavenDB(provider.FormData[0]);
                    Sample newSample;
                    using (StreamReader sr = new StreamReader(file.LocalFileName))
                    {
                        String name = sr.ReadLine();
                        String peaks = sr.ReadToEnd();
                        newSample = new Sample(name);
                        newSample.PeaksFromCSV(peaks);
                        newSample.Shard = provider.FormData[0];
                    }
                    using (var data = File.Open(file.LocalFileName, FileMode.Open))
                    {
                        DB.StoreSample(newSample, data);
                    }
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
    }
}
